<template>
  <div class="app">
    <!-- 搜索栏 -->
    <div class="search-container">
      <a-input-search
        style="width: 500px; height: 30px; text-align: right"
        v-model="searchOption.name"
        placeholder="搜索优质农产品..."
        allow-clear
        search-button
        @search="loadProducts"
      >
        <template #button-icon>
          <icon-search />
        </template>
        <template #button-default>
          <span class="search-button">立即搜索</span>
        </template>
      </a-input-search>
    </div>

    <!-- 分类+轮播图容器 -->
    <div class="main-container">
      <!-- 商品分类 -->
      <div class="category-sidebar">
        <div class="category-header">所有分类</div>
        <div
          v-for="category in productCategoryList"
          :key="category.categoryId"
          class="category-item"
          :class="{ active: searchOption.categoryId === category.categoryId }"
          @click="handleCategoryClick(category.categoryId)"
        >
          {{ category.categoryName }}
          <icon-right class="arrow-icon" />
        </div>
      </div>

      <!-- 轮播图 -->
      <div class="carousel-container">
        <a-carousel
          :auto-play="true"
          indicator-type="dot"
          show-arrow="hover"
          animation-name="fade"
          style="height: 500px"
        >
          <a-carousel-item v-for="(image, index) in images" :key="index">
            <a-image
              :src="image"
              fit="cover"
              width="100%"
              height="100%"
              :preview="false"
            />
          </a-carousel-item>
        </a-carousel>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <a-row :gutter="[24, 24]" justify="start">
        <a-col
          v-for="(item, index) in petPage.records"
          :key="index"
          :xs="24"
          :sm="12"
          :md="8"
        >
          <a-card
            hoverable
            class="product-card"
            @click="handleCardClick(item.productId)"
          >
            <template #cover>
              <div class="image-container">
                <div class="image-wrapper">
                  <a-image
                    :src="item.coverImage"
                    :alt="item.title"
                    class="product-image"
                    :preview="false"
                  />
                </div>
                <div class="image-overlay">
                  <div class="stats">
                    <span class="stat-item">
                      <icon-eye /> {{ item.viewCount || 0 }}
                    </span>
                    <span class="stat-item">
                      <icon-shopping-cart /> {{ item.stock }}库存
                    </span>
                  </div>
                  <a-tag v-if="item.stock < 50" color="red" class="stock-tag">
                    即将售罄
                  </a-tag>
                </div>
              </div>
            </template>

            <a-card-meta>
              <template #description>
                <div class="product-content">
                  <div class="title-container">
                    {{ item.title }}
                  </div>
                  <!--                  <div class="description">{{ item.description }}</div>-->
                  <div class="price-section">
                    <span class="current-price"
                      >¥{{ item.price.toFixed(2) }}</span
                    >
                    <span class="origin-price"
                      >¥{{ (item.price * 1.2).toFixed(2) }}</span
                    >
                  </div>
                  <div class="meta-footer">
                    <a-tag color="green" class="origin-tag">
                      <icon-environment />
                      {{ item.farmerId }}号农户直供
                    </a-tag>
                    <icon-heart class="favorite-icon" />
                  </div>
                </div>
              </template>
            </a-card-meta>
          </a-card>
        </a-col>
      </a-row>

      <!-- 分页 -->
      <a-pagination
        v-if="petPage.total > 9"
        :total="petPage.total"
        :page-size="9"
        :current="petPage.current"
        show-total
        show-jumper
        class="pagination"
        @change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import {
  ProductCategoryControllerService,
  ProductControllerService,
  UserControllerService,
} from "@/generated";
import { getUserCookie, isLogin, setUserCookie } from "@/utils/auth";

const router = useRouter();

// 存储产品类别的集合
const productCategoryList = reactive([]);

// 轮播图数据
const images = [
  "http://152.136.39.163:9000/images-dev/upload/images/0b449a14-3b3b-4e35-8f5a-01d5c1080b65.jpg",
  "http://152.136.39.163:9000/images-dev/upload/images/fde43e79-621b-43cf-8f35-d32304dbc9c0.jpg",
];

// 商品分页数据
const petPage = reactive({
  records: [] as any[],
  total: 0,
  pages: 0,
  size: 9,
  current: 1,
});

// 搜索参数
const searchOption = reactive({
  name: "",
  categoryId: 0,
});

// 加载商品数据
const loadProducts = async (page = 1) => {
  console.log("搜索参数:", searchOption); // 添加调试信息
  try {
    const res = await ProductControllerService.getProductPage({
      pageNumber: page,
      pageSize: petPage.size,
      title: searchOption.name,
      categoryId: searchOption.categoryId,
      shelfStatus: 1,
    });

    console.log("后端响应:", res); // 添加调试信息

    if (res.code === 0) {
      Object.assign(petPage, {
        records: res.data?.records || [],
        total: res.data?.total || 0,
        current: page,
      });
    }
  } catch (error) {
    console.error("加载商品失败:", error);
  }
};

// 分页变化处理
const handlePageChange = (page: number) => {
  loadProducts(page);
};

// 分类点击处理
const handleCategoryClick = (categoryId: number) => {
  searchOption.categoryId =
    categoryId === searchOption.categoryId ? 0 : categoryId;
  loadProducts();
};

// 跳转详情页
const handleCardClick = (productId: number | undefined) => {
  if (!isLogin()) {
    router.push("/common/login");
    return;
  }
  if (productId) {
    router.push(`/product/productDetails/${productId}`);
  }
};

// 获取当前用户
const getCurrentUser = async () => {
  try {
    const res = await UserControllerService.getCurrentUser();
    if (res.code === 0) {
      setUserCookie(res.data);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 获取所有产品类别
const getAllProductCategory = async () => {
  try {
    const res = await ProductCategoryControllerService.getProductCategoryList();
    if (res.code === 0) {
      productCategoryList.push(...res.data);
      console.log("信息", productCategoryList);
    }
  } catch (error) {
    console.error("获取产品类别失败:", error);
  }
};

// 当检测到searchOption.name的值变化时，重新加载商品数据
watch(
  () => searchOption.name,
  () => {
    loadProducts();
  }
);

onMounted(() => {
  loadProducts();
  getCurrentUser();
  getAllProductCategory();
});
</script>

<style scoped>
.app {
  max-width: 1440px;
  margin: 0 auto;
  padding: 0 24px;
}

.search-container {
  margin: 40px 0 20px;
  display: flex;
  justify-content: center;
}

.main-container {
  display: flex;
  gap: 24px;
  margin: 20px 0;
}

.category-sidebar {
  width: 240px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px 0;
}

.category-header {
  padding: 0 16px 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-1);
  border-bottom: 1px solid var(--color-neutral-3);
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  color: var(--color-text-2);

  &:hover {
    background: var(--color-fill-2);
    color: var(--color-primary-6);

    .arrow-icon {
      opacity: 1;
    }
  }

  &.active {
    color: var(--color-primary-6);
    font-weight: 500;
    background: var(--color-primary-light-1);
  }
}

.arrow-icon {
  opacity: 0;
  transition: opacity 0.2s;
  color: var(--color-text-3);
}

.carousel-container {
  flex: 1;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 商品列表优化 */
.product-list {
  margin: 32px 0;
}

.product-card {
  height: 380px;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(0, 0, 0, 0.04);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px -4px rgba(0, 0, 0, 0.12);
  }
}

:deep(.arco-card-body) {
  padding: 12px !important;
}

.image-container {
  position: relative;
  flex-shrink: 0;

  .image-wrapper {
    position: relative;
    padding-top: 66.66%; /* 3:2比例 */
    border-radius: 8px;
    overflow: hidden;
    transition: transform 0.3s ease;
  }

  .product-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .image-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 12px;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.5));

    .stats {
      color: white;
      font-size: 12px;
      gap: 12px;

      .stat-item {
        padding: 4px 8px;
        background: rgba(0, 0, 0, 0.4);
        border-radius: 4px;
        backdrop-filter: blur(4px);
      }
    }

    .stock-tag {
      font-size: 12px;
      padding: 4px 8px;
    }
  }
}

.product-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 12px;
}

.title-container {
  font-size: 14px;
  font-weight: 600;
  line-height: 1.4;
  margin-bottom: 6px;
  min-height: 40px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  color: #1a1a1a;
}

.price-section {
  margin-top: -10px;
  padding-top: -50px;

  .current-price {
    color: #f76707;
    font-size: 16px;
    font-weight: 700;
  }

  .origin-price {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    text-decoration: line-through;
    margin-left: 6px;
  }
}

.meta-footer {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .origin-tag {
    font-size: 11px;
    padding: 4px 8px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    color: #495057;
  }

  .favorite-icon {
    color: rgba(0, 0, 0, 0.25);
    font-size: 16px;
    transition: all 0.2s;

    &:hover {
      color: #ff4d4f;
      transform: scale(1.15);
    }
  }
}

/* 分页样式 */
.pagination {
  margin: 32px 0;
  justify-content: center;
}

@media (max-width: 768px) {
  .product-card {
    height: 340px;
  }

  .title-container {
    font-size: 13px;
    min-height: 36px;
  }

  .description {
    font-size: 11px;
    min-height: 48px;
  }

  .price-section {
    .current-price {
      font-size: 15px;
    }

    .origin-price {
      font-size: 11px;
    }
  }

  .meta-footer {
    .origin-tag {
      font-size: 10px;
    }

    .favorite-icon {
      font-size: 14px;
    }
  }
}
</style>
